/*
 * @Author: 陈宇 975155172@qq.com
 * @Date: 2024-08-22 13:34:28
 * @LastEditors: 陈宇 975155172@qq.com
 * @LastEditTime: 2024-08-23 08:52:48
 * @FilePath: \blog-web\src\axios\config.ts
 * @Description: 请求拦截处理入参 响应拦截处理出参
 */
import type { AxiosResponse, InternalAxiosRequestConfig } from './types'
import qs from 'qs'
import { Message } from '@arco-design/web-vue';
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants'
import { objToFormData } from '@/utils'

// 请求拦截
const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (config.method === 'post') {
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    } else if (
      TRANSFORM_REQUEST_DATA &&
      config.headers['Content-Type'] === 'multipart/form-data' &&
      !(config.data instanceof FormData)
    ) {
      config.data = objToFormData(config.data)
    }
  }

  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

// 响应拦截
const defaultResponseInterceptors = (response: AxiosResponse) => {
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (response.data.code === SUCCESS_CODE) {
    return response.data
  } else {
    Message.clear();
    Message.error(response?.data?.message)
    if (response?.data?.code === 401) {
      // 此处退出登录
    }
    return Promise.reject(new Error(response?.data?.message));
  }
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
